import {React,Fragment,useState,useEffect,useRef} from 'react';
import moment from 'moment';
import {Table,Button,Space,Input,Modal,message,Form} from 'antd';
import {SearchOutlined,EditOutlined,DeleteOutlined} from '@ant-design/icons';
import {inject,observer} from 'mobx-react';
import './Suppierset.css'



// 成功提示框
const success = (value) => {
  message.success(value);
};
// 失败提示
const error = (value) => {
  message.error(value);
};
//列名 
const mapFieldToChinese = {
  id:'序号',
  supplierName:'供应商名称',
  supplierCode:'供应商编码',
  supplierPhone:'联系电话',
  contacts:'联系人',
  address:'地址',
  email:'邮箱'
}
// 复选
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User',
    // Column configuration not to be checked
    name: record.name,
  }),
};

function Suppierset(props) {

  // 
      const [id,setId] = useState()//获取序号
      const searchRef = useRef()//获取查询内容

      // 添加xiugai框状态
      const [add, setAdd] = useState(false);
      const [addEdit,setAddEdit]=useState('')//判断是添加还是修改
        // 删除提示模态框
      const [del, setDel] = useState(false);
      // 添加修改
      let obj = '';
      function addEditInfo(fun){
        let values = obj
        values.id = id
        values.fun = fun
        props.Supplier.addEditSupplier(values).then((res)=>{
          if(res.code==200){
            success(res.msg)
          }
          getList()
        }).catch((err)=>{
            error(err.msg)
          console.log(err);
        })
      }

      const [form] = Form.useForm();
      //此为Modal点击确定以后的回调
      const okHandle = async () => {
        const fieldsValue = await form.validateFields();
        //fieldsValue即为表单内的值
        obj = fieldsValue;
        addEditInfo(addEdit);
        console.log(obj);
        console.log("okHandle -> fieldsValue", fieldsValue)
        form.resetFields();
      };
      // 删除
      function delInfo(){
        let values = {
          id:id
        }
        props.Supplier.delSupplier(values).then((res)=>{
          console.log(res);
          if(res.code==200){
            success(res.msg)
          }
          getList()
        }).catch((err)=>{
          console.log(err);
          error(err.msg)
        })
      } 
      
      // 查询
      function searchInfo() {
        let values = {
            supplierName:searchRef.current.state.value
        }
        props.Supplier.searchSupplier(values).then((res)=>{
          if(res.code==200){
            console.log(res.data);
            setData(res.data)
            success(res.msg)
          }
        }).catch((err)=>{
          console.log(err);
          error(err.msg)
        })
      }
  // 渲染table
      const [selectionType, setSelectionType] = useState('checkbox');
      const [loading,setLoading] = useState(false)
      const [columns,setColumns] = useState([]);
      const [data,setData] = useState([]);
      function getList(){
        props.Supplier.getSupplierList().then((res)=>{
          let keys = Object.keys(res.data[0]);
          let cols = keys.map(item=>{
              return {
                width: 150,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center'
              }   
          })
          cols.push({
            width:160,
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            fixed: 'right',
            render: ()=>{
                return(
                  <Space>
                  <Button type='primary' shape="circle" icon={<EditOutlined />} onClick={() => {setAdd(true);setAddEdit(1);}}></Button>
                  <Button onClick={()=>{setDel(true)}} icon={<DeleteOutlined />} shape="circle" type='danger'></Button>
                </Space>
                )
            }
          })
          setColumns(cols)
          setData(res.data)
        }).catch((err)=>{
          console.log(err);
        }).finally(()=> {setLoading(false);})
      }
      
      useEffect(()=>{
        setLoading(true)
        getList();
      },[]);
    return (
        <Fragment>
            <h3>供应商基础设置</h3>
            <Table 
            loading={loading}
            rowSelection={{
            type: selectionType,
                ...rowSelection,
            }} bordered='true' 
            title={() => {return (<Fragment>
              <h4>供应商基本资料</h4>
              <div className='tableHeader'>
                <div>
                  <Input className='search' ref={searchRef} placeholder="请输入供应商名称" prefix={<SearchOutlined />}/>
                  <Button type='primary' onClick={searchInfo}>查询</Button>
                </div>
                <Button type='primary' onClick={() => {setAdd(true);setAddEdit(0)}}>新增供应商</Button>
              </div>
              </Fragment>)}} 
            onRow = {(record) => {
              return {
                onClick: () => {
                  setId(record.id)
                  }
                }
              }
            }
            columns={columns} dataSource={data} rowKey={(record) => `id${record.id}`} pagination={{ pageSize: 10 }} scroll={{ y: 400 }}></Table>
            {/* 删除提示 */}
            <Modal title="删除提示" 
            visible={del}
            okText= '确定'
            cancelText= '取消'
            onOk={() => {
              delInfo()
              setDel(false)
            }}
            onCancel={() => {setDel(false)}}
            >
              <p>你确定要删除这条信息吗</p>
            </Modal>
            {/* 添加修改框 */}
            <Modal
              title="详细信息"
              centered
              visible={add}
              okText= '确定'
              cancelText= '取消'
              onOk={() => {
                setAdd(false);
                okHandle();
                // addEditInfo(addEdit);
              }}
              onCancel={() => {setAdd(false);}}
              width={1000}
            >
          <Form
            form={form}
            name="customerInfo"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            autoComplete="off"
          >
        <div className='addModal'>
                <div>
                <Form.Item
                  label="供应商名称："
                  name="supplierName"
                  
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="供应商编码："
                  name="supplierCode"
                  
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="联系电话："
                  name="supplierPhone"
                  
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>

                <div>
                <Form.Item
                  label="联系人："
                  name="contacts"
                  
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="地址："
                  name="address"
                 
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="邮箱："
                  name="email"
                  
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>
              </div>
              </Form>
            </Modal>
        </Fragment>
    );
}

export default inject('Supplier')(observer(Suppierset))
// export default CustomerInfo;